﻿using DotNetCore.CAP;
using EventHandlerDemo.Domain.Bases.UOW;
using Microsoft.EntityFrameworkCore.Storage;

namespace EventHandlerDemo.Infrastructure.EFCore
{
    public class EFCoreUnitOfWork : IOuterUnitOfWork
    {
        private readonly AppDbContext _dbContext;
        private readonly ICapPublisher _capBus;
        protected IDbContextTransaction? DbContextTransaction { get; set; }

        public string Id => Guid.NewGuid().ToString();

        public bool IsDisposed { get; private set; }

        public IOuterUnitOfWork Outer { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }

        public EFCoreUnitOfWork(AppDbContext dbContext, ICapPublisher capBus)
        {
            _dbContext = dbContext;
            _capBus = capBus;
        }

        public void BeginTransaction()
        {
            DbContextTransaction = _dbContext.Database.BeginTransaction(_capBus, autoCommit: false);
        }

        public async Task CompleteAsync()
        {
            try
            {
                await SaveChangesAsync();
                await CommitTransactionAsync();
            }
            catch (Exception ex)
            {
                await RollbackAsync();
                throw ex;
            }
        }

        public async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
        {
            var result = await _dbContext.SaveChangesAsync(cancellationToken);
            return result;
        }

        public async Task CommitTransactionAsync(CancellationToken cancellationToken = default)
        {
            _capBus.Publish("sample.rabbitmq.mysql", DateTime.Now);
            //如果此处出现异常，则整个事务回滚，不会执行到数据库中
            //throw new Exception("test");
            await DbContextTransaction!.CommitAsync(cancellationToken);
        }

        public async Task RollbackAsync()
        {
            await DbContextTransaction!.RollbackAsync();
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (DbContextTransaction is not null)
                {
                    DbContextTransaction.Dispose();
                    DbContextTransaction = null;
                }
            }
        }
    }
}
